package com.fan.configService.controller;


import com.fan.configService.config.Constant;
import com.fan.configService.controller.Request.UserRequest;
import com.fan.configService.exception.QhException;
import com.fan.configService.exception.QhUserErrors;
import com.fan.configService.po.User;
import com.fan.configService.service.UserService;
import com.fan.configService.service.redis.RedisOperator;
import com.fan.configService.shiro.JwtHelper;
import com.fan.configService.vo.ResponseResult;
import com.fan.configService.vo.UserVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

@Api(tags = "登录")
@RestController
@RequestMapping
public class LoginController {
    @Autowired
    UserService userService;
    @Autowired
    Constant constant;
    @Autowired
    RedisOperator redisOperator;


    @ApiOperation(value = "登录", notes = "用户登录")
    @PostMapping("/login")
    public ResponseResult<UserVo> login(@RequestBody UserRequest userRequest) {
        String attribute = redisOperator.get(constant.getGeetestLib().concat("_").concat(userRequest.getSessionId()));
        ResponseResult<UserVo> responseResult = new ResponseResult();
        if (StringUtils.isBlank(attribute)) {
            throw new QhException(QhUserErrors.VERIFICATION_NO_PASSED);
        }
        User user = userService.findUserByLoginName(userRequest.getLoginName());
        if (!StringUtils.equals(userRequest.getPassword(), user.getPassword())) {
            throw new QhException(QhUserErrors.USER_ERROR);
        }
        UserVo userVo = new UserVo();
        BeanUtils.copyProperties(user, userVo);
        String jwt = JwtHelper.createJWT(user.getUserId().toString(), "aaa", null, null, 1800000l, JwtHelper.SIGNATURE);
        userVo.setToken(jwt);
        responseResult.setData(userVo);
        return responseResult;
    }


    @ApiIgnore
    @GetMapping("/overTime")
    public ResponseResult overTime() {
        ResponseResult responseResult = new ResponseResult();
        responseResult.setCode(-1);
        responseResult.setMsg("登录超时");
        return responseResult;
    }

    @ApiIgnore
    @GetMapping("/tokenIsNull")
    public ResponseResult tokenIsNull() {
        ResponseResult responseResult = new ResponseResult();
        responseResult.setCode(-1);
        responseResult.setMsg("token为空");
        return responseResult;
    }

    @ApiIgnore
    @GetMapping("/tokenValidate")
    public ResponseResult tokenValidate() {
        ResponseResult responseResult = new ResponseResult();
        responseResult.setCode(-1);
        responseResult.setMsg("token验证失败");
        return responseResult;
    }
}
